<template>
  <div class="create_order_1 w1200">
    <div class="step_bar">
      <div class="step">
        <div class="item check">
          <el-icon>
            <Shop />
          </el-icon>
          我的购物车
        </div>
        <div class="item check">
          <el-icon>
            <MessageBox />
          </el-icon>
          物流地址
        </div>
        <div class="item">
          <el-icon>
            <Money />
          </el-icon>
          选择支付
        </div>
        <div class="item">
          <el-icon>
            <CircleCheckFilled />
          </el-icon>
          支付成功
        </div>
      </div>
    </div>

    <!-- 地址信息选择 S -->
    <div class="block">
      <div class="change-address">
        <div class="title">选择送货地址</div>
        <el-button size="small" link @click="$router.push('/user/address')">添加地址</el-button>
      </div>
      <div class="address_list" v-if="addressStore.addressList.length > 0">
        <ul>
          <li :class="{ red: isActiveAddressId ? isActiveAddressId === v.id : v.isDefault === 1 }" v-for="(v, k) in addressStore.addressList" :key="k" @click="checkAddress(v)">
            <div class="receive_name">
              {{ v.name }}
              <span>{{ v.phone }}</span>
            </div>
            <div class="area_info">{{ v.allAddress }}</div>
            <div class="cmarker"><img :src="isActiveAddressId == v.id ? '/src/assets/Home/checkAddress.png' : '/src/assets/Home/checkAddress2.png'" alt="" /></div>
          </li>
        </ul>
      </div>

      <div class="empty_address" v-else>
        没有设置收货地址，请先前往
        <router-link to="/user/address">设置</router-link>
      </div>
    </div>
    <!-- 地址信息选择 E -->

    <!-- 预生成订单信息 S -->
    <div class="block">
      <div class="title">商品信息</div>
      <div class="goods_list">
        <div class="goods_th">
          <el-row>
            <el-col :span="10">商品信息</el-col>
            <el-col :span="4">属性信息</el-col>
            <el-col :span="4">单价</el-col>
            <el-col :span="2">数量</el-col>
            <el-col :span="2">优惠</el-col>
            <el-col :span="2">小计</el-col>
          </el-row>
        </div>

        <div class="store_list" v-for="(v, k) in 1" :key="k">
          <div class="store_title">
            <div>
              <router-link to="'/" class="float_left">
                <img class="float_left" src="/src/assets/Home/default_store_image.png" alt="" />
                <span class="float_left">店铺名称</span>
              </router-link>
              <div v-if="true" class="float_right coupon_order">
                <el-icon color="#ca151e" size="18">
                  <PriceTag />
                </el-icon>
                优惠券：
                <el-select style="width: 130px; margin-right: 10px">
                  <!--                  <el-option :value="0" label="不使用优惠券"></el-option>-->
                  <!--                  <el-option v-for="(val, key) in 2" :key="key" label="余额 + 优惠券"></el-option>-->
                </el-select>
              </div>
              <div class="clear"></div>
            </div>

            <div class="og_list">
              <ul>
                <li v-for="(vo, key) in goodsList" :key="key">
                  <el-row>
                    <el-col :span="10">
                      <dl>
                        <dt><img src="" alt="" /></dt>
                        <dd title="">{{ vo.skuName || vo.goodsName }}</dd>
                      </dl>
                    </el-col>
                    <el-col :span="4">
                      <div class="goods_info_th">--</div>
                    </el-col>
                    <el-col :span="4">
                      <div class="goods_info_th">{{ vo.price }}</div>
                    </el-col>
                    <el-col :span="2">
                      <div class="goods_info_th">{{ vo.count }}</div>
                    </el-col>
                    <el-col :span="2">
                      <div class="goods_info_th">-</div>
                    </el-col>
                    <el-col :span="2">
                      <div class="goods_info_th red">&yen;{{ (vo.price * vo.count).toFixed(2) }}</div>
                    </el-col>
                  </el-row>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
      <el-form :model="form">
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" rows="3" />
        </el-form-item>
      </el-form>
      <!--      <div class="remark">-->
      <!--        <div class="goods_th">备注</div>-->
      <!--        <div class="remark_input">-->
      <!--          <textarea cols="60" rows="3"></textarea>-->
      <!--        </div>-->
      <!--      </div>-->

      <div class="sum_block">
        <div class="total">
          总金额：<span>￥{{ cartStore.selectedMoney?.toFixed(2) }}</span
          >( 不包含运费和优惠 )
        </div>
        <!--        <div @click="createOrder">{{ data.loading ? '加载中..' : '创建订单' }}</div>-->
        <el-button @click="createOrder" type="primary" size="large" style="margin: 20px 0">创建订单</el-button>
        <div class="clear"></div>
      </div>
    </div>
    <!-- 预生成订单信息 E -->
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref, toRefs } from 'vue';
import { useCartStore } from '@/store/modules/carts';
import { useUserStore } from '@/store';
import { useAddressStore } from '@/store/modules/address';
import { useRoute, useRouter } from 'vue-router';
import { CircleCheckFilled, MessageBox, Money, PriceTag, Shop } from '@element-plus/icons-vue';
import { addOrdersApi } from '@/api/user/orders';

const route = useRoute();
const router = useRouter();
const cartStore = useCartStore();
const userStore = useUserStore();
const addressStore = useAddressStore();
const goodsList = ref<any>([]);
const isActiveAddressId = ref(null);

const initFormData: any = {
  userId: userStore.user.userId,
  couponId: '', //优惠券日志ID
  collectiveId: '', //拼团日志ID
  orderNo: '', //订单号
  orderGoodsId: '', //订单商品
  totalPrice: '', //总支付金额
  orderPrice: '', //订单计算金额
  orderBalance: '', //余额支付金额
  freightMoney: '', //运费金额
  orderStatus: 1, //订单支付 0 取消 1 等待支付 2等待发货 3确认收货 4等待评论 5售后 6订单完成
  refund_status: null, //0 退款 1退货 2 处理结束
  isSettlement: null, //是否结算
  deliveryNo: null, //快递订单号
  deliveryCode: null, //快递公司编码
  receiveName: '', //收件人名
  receiveTel: '', //收件人手机
  receiveArea: '', //地址信息
  receiveAddress: '', //详细地址信息
  paymentName: '', //支付方式
  remark: '', //备注
  tenantId: '' //租户
};
const data = reactive<any>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 4,
    isDefault: null,
    userId: userStore.user.userId
  }
});
const { queryParams, form } = toRefs(data);

/*获取父组件路由传参*/
const fetchData = () => {
  const fullPath = route.fullPath; //获取完整路径
  const paramsStart = fullPath.lastIndexOf('/') + 1; //找到参数开始的索引
  const endCodedParams = fullPath.substring(paramsStart); //提取参数字符串
  const decodeParams = decodeURIComponent(endCodedParams); //解码参数字符串
  const params = JSON.parse(decodeParams); //解析为JS对象
  goodsList.value = params.order;
  console.log(params);
  // 赋值订单金额-商品信息
  form.value.orderPrice = cartStore.selectedMoney;
  //遍历params.order，取出里面的skuId,再将ID用逗号拼接成子符串，并赋值给form.value.orderGoodsId
  form.value.orderGoodsId = params.order.map((item: any) => item.skuId).join(',');
};

/*默认收货地址*/
const getDefaultArea = () => {
  //遍历addressStore.addressList,取出isDefault=1的对象，
  const defaultArea = addressStore.addressList.find((item) => item.isDefault === 1);
  //再对form.value对进行赋值
  if (defaultArea) {
    isActiveAddressId.value = defaultArea.id;
    form.value.receiveName = defaultArea.name;
    form.value.receiveTel = defaultArea.phone;
    form.value.receiveArea = defaultArea.provinceName + defaultArea.cityName + defaultArea.districtName + defaultArea.address;
    form.value.receiveAddress = defaultArea.allAddress;
  }
};

/*切换收货地址则重新赋值*/
const checkAddress = (v: any) => {
  // 赋值订单-地址信息,未切换地址时使用默认地址信息参数
  isActiveAddressId.value = v.id;
  form.value.receiveName = v.name;
  form.value.receiveTel = v.phone;
  form.value.receiveArea = v.provinceName + v.cityName + v.districtName + v.address;
  form.value.receiveAddress = v.allAddress;
};
/*创建订单*/
const createOrder = async () => {
  //TODO 1.这里要根据商品查询到租户ID，然后再把租户ID赋值给form.value.tenantId
  //TODO 2.判断这个订单中的商品是否涉及有多个租户，如果有，则需要将订单进行拆分
  let params = {
    //这里应该只需传递订单金额
    order: goodsList.value,
    address: 1 //收货地址ID
  };
  //1.将params组合成JSON字符
  let str = encodeURIComponent(JSON.stringify(params));
  //2通过API创建数据库订单
  console.log(form.value);
  const res = await addOrdersApi(form.value);
  console.log(res);
  if (res.code === 200) {
    //清除购物车中已生成订单的商品数据
    //3.通过router.push把参数传递给订单支付页面
    router.push('/user/order/pay/' + str);
  }
};

onMounted(() => {
  fetchData();
  getDefaultArea();
  addressStore.getAddressList(queryParams.value);
});
</script>

<style scoped lang="scss">
.step_bar {
  margin: 40px 0;

  .step {
    height: 46px;
    line-height: 46px;
    background: #f5f7fa;
    margin-bottom: 50px;
    display: flex;
  }

  .step .item {
    font-size: 16px;
    color: #c0c4cc;
    flex: 1;
    justify-content: center;
    align-items: center;
    display: flex;

    i {
      margin-right: 10px;
    }

    text-align: center;
    border-right: 4px solid #fff;
  }

  .step .item.check {
    color: #333;
    font-weight: bold;
  }
}

.block {
  .change-address {
    display: flex;
    align-content: center;
  }

  .title {
    font-size: 16px;
    clear: both;
    font-weight: bold;
    padding-bottom: 20px;
  }

  .store_list {
    margin-top: 20px;

    .og_list {
      margin-top: 20px;
      color: #666;
      font-size: 12px;
      border: 1px solid #efefef;
      padding: 20px 0;
      line-height: 40px;

      li {
        margin-bottom: 15px;
        padding-bottom: 15px;
        border-bottom: 1px solid #efefef;

        &:last-child {
          margin-bottom: 0;
          padding-bottom: 0;
          border-bottom: none;
        }
      }

      .red {
        color: #ca151e;
      }

      dl {
        &:after {
          clear: both;
          display: block;
          content: '';
        }

        dt {
          width: 40px;
          height: 40px;
          display: block;
          float: left;
          background: #f8f8f8;
          margin-right: 15px;
          margin-left: 20px;
          border: 1px solid #efefef;

          img {
            margin: 0;
            width: 100%;
            height: 100%;
            border-radius: 0;
            vertical-align: unset;
          }
        }

        dd {
          float: left;
          width: 400px;
          height: 40px;
          text-overflow: hidden;
          line-height: 20px;
        }
      }

      .goods_info_th {
        text-indent: 20px;
      }
    }

    .store_title {
      img {
        width: 35px;
        height: 35px;
        margin-right: 10px;
        margin-left: 20px;
        border-radius: 50%;
      }

      span {
        line-height: 35px;
      }
    }
  }

  .sum_block {
    text-align: right;

    .total {
      line-height: 60px;

      span {
        font-size: 28px;
        color: #ca151e;
        margin-right: 16px;
      }
    }

    .btn {
      background: #ca151e;
      color: #fff;
      border-radius: 3px;
      width: 80px;
      height: 30px;
      line-height: 30px;
      text-align: center;
      display: block;
      float: right;
      cursor: pointer;

      &.hide {
        background: #ccc;
        cursor: not-allowed;
        color: #666;
      }
    }
  }

  .goods_th {
    background: #f2f2f2;
    line-height: 40px;
    text-indent: 20px;
  }

  .remark {
    margin-top: 40px;

    .remark_input {
      margin: 20px 0;

      textarea {
        border-color: #cfcfcf;
        outline: none;
        border-radius: 4px;
        padding: 8px;
      }
    }
  }

  .empty_address {
    margin-bottom: 80px;
    line-height: 100px;
    border: 3px solid #efefef;
    border-radius: 3px;
    text-align: center;
    width: 292px;
    height: 105px;

    a {
      font-weight: bold;
      color: #ca151e;
    }
  }

  .address_list {
    margin-bottom: 30px;

    ul {
      &:after {
        clear: both;
        content: '';
        display: block;
      }

      li {
        cursor: pointer;
        float: left;
        box-sizing: border-box;
        width: 292px;
        height: 105px;
        border-radius: 3px;
        border: 2px solid #efefef;
        margin-right: 10px;
        margin-bottom: 10px;
        padding: 20px;
        position: relative;
        color: #666;

        &:nth-child(4n) {
          margin-right: 0;
        }

        .receive_name {
          margin-bottom: 10px;
          font-weight: bold;
          line-height: 18px;
          color: #333;

          span {
            font-weight: normal;
          }
        }

        .cmarker {
          position: absolute;
          right: -16px;
          bottom: -17px;
          font-size: 30px;
          color: #333;
        }

        &.red {
          border-color: #ca151e;

          .cmarker {
            color: #ca151e;
          }
        }
      }
    }
  }
}

.coupon_order {
  display: flex;
  align-items: center;
  color: #ca151e;

  i {
    margin-right: 5px;
  }
}
</style>
